package com.duguo.dynamicmvc.factory.stage;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import com.duguo.dynamicmvc.factory.ControllerBuilder;
import com.duguo.dynamicmvc.factory.ControllerFactory;
import com.duguo.dynamicmvc.factory.WorkingModel;
import com.duguo.dynamicmvc.factory.processor.ProcessorHolder;
import com.duguo.dynamicmvc.factory.processor.controller.ControllerNameBuilder;
import com.duguo.dynamicmvc.factory.processor.register.RegisterProcessor;

public class RegisterControllerBeansStage implements Stage,BeanFactoryAware {
	
	BeanFactory _beanFactory;

    public void execute(ControllerFactory controllerFactory) throws Exception {
    	WorkingModel workingModel=controllerFactory.getWorkingModel();
        if (workingModel.isRootController()) {
            registerControllerBeans(workingModel);
        }
    }


    private void registerControllerBeans(WorkingModel workingModel) throws Exception {
    	ControllerBuilder controllerBuilder=workingModel.getControllerBuilder();
    	ProcessorHolder processorHolder = controllerBuilder.getProcessorHolder();
		ControllerNameBuilder controllerNameBuilder=processorHolder.getControllerProcessor().getControllerNameBuilder();
    	RegisterProcessor registerProcessor=processorHolder.getRegisterProcessor();
    	Object rootController=workingModel.getControllerInstance();
    	
        for (String controllerPath : controllerBuilder.getControllerFactoryBeans().keySet()) {
            if (controllerNameBuilder.isRootController(controllerPath))
                continue;

            ControllerFactory controllerFactory = (ControllerFactory)_beanFactory.getBean("&"+controllerPath);
            if(!controllerFactory.getWorkingModel().isDynamicController()){
	            Object controllerBean = _beanFactory.getBean(controllerPath);
	            registerProcessor.registerControllerBean(rootController, controllerPath, controllerBean);
            }
        }
    }

	public void setBeanFactory(BeanFactory beanFactory) {
		_beanFactory = beanFactory;
	}
}
